--
-- Author:      name
-- DateTime:    2018-05-28 15:57:48
-- Description: 游戏主逻辑


local skynet = require "skynet"
local log = require "Log"
local config = require "configquery"
local json = require "cjson"
local Timer = require "timer"
local pbc = require "pbc_helper"
local parser = require "parser"
local protobuf = require "protobuf"
local pack_helper = require "pack_helper"
local FSM = require "fsm"
local Universal = require "Universal"
local NodeMessage = require "NodeMessage"
require "common"


local mix_array = mix_array
local table_clone = table_clone
local arr_toset = arr_toset
local floor = math.floor
local four_five = math.four_five
local random = math.random

-- local player_list 
-- local seat_list 

local testtableid = 10020
----------------------------------
-- logic
----------------------------------
local Machine = class("Machine")

function Machine:ctor(tableid,rule)
	self.close = false --关闭游戏
	self.nodeMessage = NodeMessage.new()
	self.player_list = {}
	self.seat_list = {}
	self.tableid = tableid
	self.gameid = getGameIdbyTable(tableid)
	self.roomid = getRoomType(tableid)
	local cfgname = getGameRoomConfig(self.gameid)
	local roomcfg = config[cfgname][self.roomid]
	--配置信息
	self.maxSeatNum = roomcfg.player_num --最大座位数
	self.bottomNum = roomcfg.bottom_score * 0.01 --底分
	self.tipRate = roomcfg.tip * 0.01 --服务费比
	self.incomeRate = 1 - self.tipRate --收入占比
	self.minChip = roomcfg.min_coin --入场最低分
	self.topChip = roomcfg.max_coin --入场最高分
	--时间
	self.status_time = {
		wait = 1,		--等待时间
		rest = 3,		--休息时间
		start = 3,		--
		bank = 5, 	    --抢庄
		bankok = 2,     --确定庄
		bet = 5,		--下注时间
		open = 8,		--拼牌
		settlement = 10,--结算时间

	}
	self.tbBankerRate = {} --抢庄玩家列表(倍数，玩家id)
	self.tbPlayerBet = {}
	self.tbNoBanker = {} --不抢庄玩家列表
	self.playerNum = 0 --参与游戏人数
	self.tbPlayer = {} --参与游戏人
	self.bankerid = 0  --当前庄家id
	self.bankerSeatid = 0 --庄位置id
	self.bankerRate = 0 --庄倍率
	self.tbWinScore = {} --输赢情况
	self.handlerStateTime = nil --定时器句柄
	self.tbBankRates = {1,2,3,4} --可抢庄的倍数
	self.tbBetRates = {5,10,20,30} --可下注的倍数
	self.tbBetRates2 = {1,2,3,4} --下注的倍数(钱不够时的情况)
	self.maxBetRate = 30 --最大下注倍数
	self.tbPlayerComb = {} --组牌完成玩家
	self.tbChangeNum = {} --换牌次数
	self.operStartTime = 0 --当前状态的开始时间
	self.tbBeforeStart = {} --开始游戏前所捅有筹码
	
	--self.last_wins = {} --上局玩家列表
	self.gmcards = {} --配牌列表
	self.tbCheatNum = {} --每个人配牌标记
	self.tbSeatCard = {} --座位上的牌
	self.tbNiuRes = {}	--算牛结果
	self.tbPaijuMessage = {} --牌局里发给各个玩家的消息记录
	self.msgStart = false --开始记录消息
	self.tbVisitorMsg = {} --游客消息
	self.closeHandler = nil
	self.rule = rule
	self.tbProtoId = {} --协议所在proto
	self.paijuid = 0 --牌局ID
	self.messageid = 1 --发送消息id号
	self.banker = nil --庄

	--加载proto, 为牛牛重连而做的
	self:loadProto()

	self.stock = {} --库存
	self:getStock()
	print(self.stock)
	--共用类
	self.universal = Universal.new()
	--状态
	--休息，开始， 抢庄，下注，组牌，结算
	--state1 --eventName --state2 --callback
	self.gameStateTransitionTable = {
		{"rest", 		"to_start", 	"start", 		function() self:onStart() end },
		{"start", 		"to_bank", 		"bank", 		function() self:onBank() end },
		{"bank", 		"to_bankok", 	"bankok", 		function() self:onBankok() end },
		{"bankok", 		"to_bet",		"bet", 			function() self:onBet() end },
		{"bet", 		"to_open",		"open", 		function() self:onOpen() end },
		{"open", 		"to_settlement","settlement", 	function() self:onSettlement() end },
		{"settlement", 	"to_rest", 		"rest", 		function() self:onRest() end},
		{"rest", 		"to_wait", 		"wait", 		function() self:onWait() end},		
		{"wait", 		"to_rest", 		"rest", 		function() self:onRest() end},			
		
	}
	--计时器
	self.timer = Timer:new()
	--状态机
	self.fsm = FSM.new(self.gameStateTransitionTable)
	

end
---------------------------------------------------------
-- private
---------------------------------------------------------

--重置数据
function Machine:reset()
	self.tbPlayer = {}
	self.tbSeatCard = {} 
	self.tbNiuRes = {}	
	self.tbBankerRate = {}
	self.tbNoBanker = {}
	self.playerNum = 0
	self.tbPlayerBet = {}
	self.bankerid = 0
	self.bankerRate = 0
	self.tbWinScore = {}
	self.bankerSeatid = 0
	self.tbPlayerComb = {}
	self.tbBeforeStart = {}
	self.tbChangeNum = {}
	for k,v in pairs(self.player_list) do 
		v.playing = false
		v.opered = false --这一局是否有操作
		v.tbBetRates = {} --能下注的倍数
		v.tbBankRates = {} --能抢庄的倍数
	end
	self.msgStart = false
	self.messageid = 1
	self.tbPaijuMessage = {}
	self.banker = nil
end

function Machine:loadProto()
	local proto_file = skynet.getenv("proto_config")
	local protofile = 'niuniu_pack.proto'
	local protopath = proto_file..'game/'

	local function load( protofile , protopath)
		--print("######P",protofile,protopath)
		local ok, result = x_pcall(parser.register, protofile, protopath)
		if not ok then
			log.error("protobuff init:", result)
		    --return nil
		end	
		for pack_name,field in pairs(parser.cache_fields) do
			local pack_id = pack_helper.get_pack(pack_name)
			if pack_id then
				for msg_name,msg_id in pairs(field) do
					self.tbProtoId[msg_name] = {pack_name,pack_id}
				end
			end
		end		
	end
	local function loadPath( path, dirs )
		if not dirs then dirs = {''} end
		for k,dir in ipairs(dirs) do
			local dir_path = path..dir
			local file_list = dir_list(dir_path)
			load(file_list, dir_path)
		end	
	end
	loadPath(proto_file,{'game'})
	self.protobuf = protobuf
end

--状态定时器
function Machine:setTime(time,callback,loop,param)
	if self.handlerStateTime then 
		self.timer:unregister(self.handlerStateTime)
		self.handlerStateTime = nil	
	end
	if not time then 
		return 
	end
	self.handlerStateTime = self.timer:register(time , param, callback,loop)	
end

--更新大厅中传来的玩家数据
function Machine:updateProperty(playerid,data)
	local player = self.player_list[playerid]
	if not player then 
		return 
	end
	for k,v in pairs(data) do 
		player[k] = v
	end
end

function Machine:getSeatPlayer(player)
	local normalPlayer = {}
	normalPlayer.seatid = player.seatid
	normalPlayer.playerid = player.playerid
	normalPlayer.nick = player.nick
	normalPlayer.chip = ""..player.chip
	normalPlayer.silver = player.silver
	normalPlayer.face = player.face
	normalPlayer.icon = player.icon
	normalPlayer.viplevel = player.viplevel
	normalPlayer.level = player.level
	normalPlayer.playing = player.playing
	return normalPlayer
end

--更新人数
function Machine:updatePlayerNum()
	local c = self:getTablePlayerNum()
	self.nodeMessage:sendGlobalService('tablestate', 'set', self.tableid, c)
end

--桌子人数
function Machine:getTablePlayerNum()
	local c = 0
	for k,v in pairs(self.player_list) do
		c = c + 1
	end
	return c
end

-- --是否是机器要
-- function Machine:isRobot(player)
-- 	local playerid = player.playerid
-- 	if playerid > 10000000 and playerid < 10000010 then 	
-- 		player.robot = true
-- 	end
-- end

---------------------------------------------------------
-- 发送消息
---------------------------------------------------------
--消息记录
function Machine:messageRecord(playerid,data)
	local msgbody
	if self.msgStart and next(data) then
		local status
		local tbProtoId = {}
		for k,v in pairs(data) do
			tbProtoId = self.tbProtoId[k]
		end
		self.tbPaijuMessage[self.paijuid] = self.tbPaijuMessage[self.paijuid] or {}
		self.tbPaijuMessage[self.paijuid][playerid] = self.tbPaijuMessage[self.paijuid][playerid] or {}

		for k, v in pairs(data) do
			v.messageid = #self.tbPaijuMessage[self.paijuid][playerid]+1
		end
		status, msgbody = pcall(self.protobuf.encode, tbProtoId[1], data)		
		if not status then
			log.error(' niuniu Machine: encode msg body failed######'..json.encode(data))
			--return
		else	
			table.insert(self.tbPaijuMessage[self.paijuid][playerid], {
				tbProtoId[2],
				msgbody,
			})
		end
	end
	return data
end

function Machine:getMessageid(playerid)
	local tb = self.tbPaijuMessage[self.paijuid]
	if not tb then 
		return 0
	end
	tb = tb[playerid]
	if not tb then 
		return 0
	end
	return #tb
end

--发送消息给gate需要返回
function Machine:callGate(player,...)
	-- return	proxy_helper.call_gate(player.nodename,player.playerid,cmd,data)
	return	self.nodeMessage:callGate(player.nodename,player.playerid,...)
end

function Machine:sendGate(player,...)	
	self.nodeMessage:sendGate(player.nodename,player.playerid,...)
end

--发送消息给玩家
function Machine:sendMessage(playerid,data)
	--加入消息记录列表
	self:messageRecord(playerid,data)
	local player = self.player_list[playerid]
	if not player or player.disconnect or not player.ready then 
		return
	end	
	self.nodeMessage:broadcastGate(player.nodename,{playerid},data)
end

--给桌上正在玩的玩家发消息
function Machine:sendToTable(data,from)
	-- local tbReciver = {}
	-- local player
	if not from or from ~= 'ntTableInfo' then 
		self:messageRecord(0,data)
	end	
	for playerid,player in pairs(self.player_list) do 
		if player  then 			
			self:sendMessage(playerid,data)		
		end	
	end
end

function Machine:sendToAll(playerid,data)
	self:messageRecord(0,data)	
	for k,v in pairs(self.player_list) do 
		if not v.disconnect and v.ready then 			
			self:sendMessage(k,data)
		end
	end
end

function Machine:sendToOther(playerid,data)
	self:messageRecord(0,data)
	for k,v in pairs(self.player_list) do 
		if (not v.disconnect and k ~= playerid) and  v.ready then 
			self:sendMessage(k,data)		
		end
	end
end

--重连客户端所要的消息历史列表
function Machine:reconnect(playerid,args)
	local paijuid = args.paijuid
	local messageid = args.messageid
	if messageid == 0 then messageid = nil end
	local msg = {
		protoid={},
		content={},				
	}
	local protoid
	local content

	if not self.tbPaijuMessage[self.paijuid] then 
		msg.messageid = 1
		return msg
	end
	local tbMsg = self.tbPaijuMessage[self.paijuid][playerid]
	if not paijuid or paijuid ~= self.paijuid or not messageid then 
		for k,v in pairs(tbMsg) do 			
			protoid = v[1]
			content = v[2]
			table.insert(msg.protoid,protoid)
			table.insert(msg.content,content)
		end		
	else
		for i=messageid ,#tbMsg do 
			if tbMsg[i] and next(tbMsg[i]) then 
				protoid = tbMsg[i][1]
				content = tbMsg[i][2]
				table.insert(msg.protoid,protoid)
				table.insert(msg.content,content)
			end
		end
	end
	-- print("#######tbMsg",tbMsg)
	msg.messageid = messageid or 1
	if protoid then 
		return msg
	end
	if paijuid == self.paijuid then 
		return msg
	end	
	return nil
end

--未入局游戏消息
function Machine:visitorMsg()
	local msg = {
		protoid={},
		content={},				
	}
	local protoid
	local content
	if not self.tbPaijuMessage[self.paijuid] then 
		return msg
	end
	local tbMsg = self.tbPaijuMessage[self.paijuid][0]
	for k,v in pairs(tbMsg) do 		
		protoid = v[1]
		content = v[2]
		-- print("############decode######",protoid,self.protobuf.decode('niuniu_pack',content))
		table.insert(msg.protoid,protoid)
		table.insert(msg.content,content)
	end
	--print("#######tbMsg",tbMsg)
	if protoid then 
		return msg
	end
	return nil
end


---------------------------------------------------------
-- 状态
---------------------------------------------------------
--等侍
function Machine:onWait()
	print("_______wait___")
	self:setTime(self.status_time.wait,function() self:waitCallback() end,true)
end
function Machine:waitCallback()
	local timehandler = nil
	if timehandler then
		return 
	end
	self:removeDisconnect()
	--人数足2个才开始
	local num = 0
	for k,v in pairs(self.player_list) do 
		num = num + 1
	end
	if num < 2  then 
		return
	end		
	--
	local callback2 = function ()
		if self:getState() ~= 'wait' then 
			return 
		end		
		self.fsm:fire("to_rest")			
	end
	timehandler = self.timer:register(self.status_time.wait,nil,callback2)
end


--休息
function Machine:onRest()
	print("_______rest___")
	self.operStartTime = os.time()
	self:ntRest()
	--洗牌
	self.rule:shuffle()
	--重置数据
	self:reset()
	self:removePlayer()
	local function checkPlayer()		
		--人数足2个才开始
		local num = 0
		for k,v in pairs(self.player_list) do 
			if not v.disconnect and v.ready then 
				num = num + 1
			end
		end
		if num < 2 then 
			self.fsm:fire("to_wait")
			return false
		end	
		if self.close then 
			return false
		end		
		return true		
	end
	if not checkPlayer() then 
		return 
	end
	local callback = function ()
		if not checkPlayer() then 
			return 
		end
		self.fsm:fire("to_start")
	end
	self:setTime(self.status_time.rest,callback)	
end

--开始
function Machine:onStart()
	--print("_______start")	
	self.msgStart = true
	self.paijuid = getRoundId(self.tableid)
	self.operStartTime = os.time()

	local callback = function()
		self.fsm:fire("to_bank")
	end
	self:setTime(self.status_time.start,callback)
	local player 
	for k,v in pairs(self.seat_list) do 
		if self.player_list[v].ready then 
			self.tbPlayer[k] = v --准备好的玩家
			player = self.player_list[v]
			player.playing = true
			player.tbBetRates = {} --玩家可以下的注
			player.tbBankRates = {}
			self.tbBeforeStart[v] = player.chip
		end
	end
	self.playerNum = table.size(self.tbPlayer)
	
	--推送当前桌子状态
	self:ntTableInfo()
	local tbCard = {}
	--self.messageid = self.messageid + 1
	for k,v in pairs(self.tbPlayer) do 
		--发牌
		self.tbSeatCard[k] = self:getCard(v,5) --self.rule:getCard(4)
		self.tbNiuRes[k] = self.rule:getNiu(self.tbSeatCard[k])

		--发牌4张
		tbCard = {}
		for i=1,4 do 
			table.insert(tbCard,self.tbSeatCard[k][i])
		end
		self:ntStart(v,tbCard)
	end

	--游客消息
	self:ntStart(0)

end

--抢庄
function Machine:onBank()
	--print("_______抢庄")	
	self.operStartTime = os.time()
	local callback = function()
		--没人抢庄,随机一个玩家做庄，1倍
		if #self.tbBankerRate == 0 then 		
			local tb = {}
			for k,v in pairs(self.tbPlayer) do 
				table.insert(self.tbBankerRate,{1,v})
			end		
		end
		if #self.tbBankerRate > 1 then 
			local sortfun = function(a,b)
				return a[1] > b[1]
			end			
			-- print(self.tbBankerRate)
			table.sort(self.tbBankerRate,sortfun)
		end
		if #self.tbBankerRate > 0 then 
			local tbRater = self.tbBankerRate[1]
			local tbBankPlayer = {tbRater[2]} --抢庄玩家多个
			local tbSeat = {self:getPlayerSeatId(tbRater[2])}
			for k,v in pairs(self.tbBankerRate) do 	
				if v[1] == tbRater[1] and v[2] ~= tbRater[2]  then 
					table.insert(tbBankPlayer,v[2])
					table.insert(tbSeat,self:getPlayerSeatId(v[2]))
				end
			end
			table.mix(tbBankPlayer)
			self.bankerid = tbBankPlayer[1]
			self.bankerRate = tbRater[1]
			self.bankerSeatid = self:getPlayerSeatId(self.bankerid)
			self.banker = self.player_list[self.bankerid]
			self:ntBankok(self.bankerid,self.bankerRate,true,tbSeat)
		end
		self.fsm:fire("to_bankok")
	end
	self:setTime(self.status_time.bank,callback)
	self:ntBank()
end

--确定抢庄
function Machine:onBankok()
	local callback = function()
		self.fsm:fire("to_bet")
	end
	self:setTime(self.status_time.bankok,callback)	
end

--下注
function Machine:onBet()
	--print("_______bet")	
	self.operStartTime = os.time()
	local player
	local callback = function()
		--如果没有押注默认最小注
		for k,v in pairs(self.tbPlayer) do 
			if not self.tbPlayerBet[v] and v ~= self.bankerid then 
				-- local rate = self.tbBetRates[1]
				player = self.player_list[v]
				self.tbPlayerBet[v] = player.tbBetRates[1]
				self:ntBetok(self:getPlayerSeatId(v),self.tbPlayerBet[v])
			end			
		end		
		self.fsm:fire("to_open")
	end
	self:setTime(self.status_time.bet,callback)	
	self:ntBet()
end

--组牌
function Machine:onOpen()
	--print("_______open")	
	self.operStartTime = os.time()
	local callback = function()
		self.fsm:fire("to_settlement")
	end
	self:setTime(self.status_time.open,callback)	
	
	-- local t = os.time()
	-- print("____checkStock____111111_")
	--检查库存,注意花时间比较多。。。
	self:checkStock()
	-- print("____checkStock____222222_",os.time() - t)
	--发牌1张
	local card
	for k,v in pairs(self.tbPlayer) do
		self.tbNiuRes[k] = self.rule:getNiu(self.tbSeatCard[k])
		card = {self.tbSeatCard[k][5]}
		self:ntComb(v,card)
	end
	for k,v in pairs(self.player_list) do 
		if v.ready and not v.playing then --旁观者
			self:ntComb(k)
		end
	end
	--游客消息
	self:ntComb(0)


end

--结算
function Machine:onSettlement()
	print("_______settlement")
	self.operStartTime = os.time()
	local banker = self.player_list[self.bankerid]
	local bankSeatid = self.bankerSeatid
	local bankNiu = self.tbNiuRes[bankSeatid]
	local bottomNum = self.bankerRate*self.bottomNum
	local player
	local settleNum = 0
	local playerWeight
	local bankWin = 0
	local res,money
	local winNum
	local reason = self.universal:getReasonId('niuniu_js')
	local callback = function()
		self.fsm:fire("to_rest")
	end
	local delay = self.status_time.settlement
	if self.playerNum == 2 then 
		delay = 6
	elseif self.playerNum == 3 then 
		delay = 7 		
	elseif self.playerNum == 4 then 
		delay = 8 
	end
	print("_##################_____#############____delay__",delay)
	self:setTime(delay,callback)
	--结算
	for k, v in pairs(self.tbPlayer) do 
		player = self.player_list[v]
		playerWeight = self.tbNiuRes[k].weight	
		--非庄玩家结算		
		if v ~= self.bankerid then 
			settleNum = bottomNum * self.tbPlayerBet[v] 
			--庄赢
			if bankNiu.weight > playerWeight then 
				--玩家输钱
				settleNum = settleNum * self.rule:getRate(bankNiu.weight) 
				settleNum = self.universal:setChip(settleNum)
				money = self:callGate(player,'change_money', -settleNum, reason)
				if money then 
					self.tbWinScore[k] = -settleNum					
					player.chip = money
					bankWin = bankWin + settleNum					
				end
			else
				--玩家赢钱
				settleNum = settleNum * self.rule:getRate(playerWeight)	
				--扣除服务费
				winNum = self.universal:setChip(settleNum*self.incomeRate)
				money = self:callGate(player, 'change_money', winNum, reason)
				if money then 
					bankWin = bankWin - settleNum
					player.chip = money
					self.tbWinScore[k] = winNum	
				end					
			end		
			print("___settleNum___",settleNum)
		end		
		if player.opered then 
			player.noOperNum = 0 
		else
			player.noOperNum = player.noOperNum + 1
		end
	end
	--庄家结算	
	if bankWin > 0 then 
		--扣除服务费
		bankWin = self.universal:setChip(bankWin*self.incomeRate)	
	else
		bankWin = self.universal:setChip(bankWin)
	end
	self.tbWinScore[bankSeatid] = bankWin
	money = self:callGate(banker,'change_money',bankWin,reason)
	if money then 
		banker.chip = money
	end
	--推送给玩家	
	self:ntEnd()
	--牌局记录
	self:paijuRecord()
	--机器人库存更新
	local system_earn,tip = self:robotSettlement()		
	if system_earn ~= 0 then 
		self.stock.pool = self.stock.pool + system_earn
		self.stock.tip = self.stock.tip + tip
		-- print("____________new stock____",self.stock)
		self:senddb('update_stock',self.stock)	
	end
	
end

-------------------------------------------------------------------------------
-- 推送消息
-------------------------------------------------------------------------------
function Machine:ntTableInfo()
	local seat_players = {}
	for seat_id,id in pairs(self.seat_list) do
		if id>0 then
			local normalPlayer = self:getSeatPlayer(self.player_list[id])	
			table.insert(seat_players,table_clone(normalPlayer))
		end
	end	

	local status = {	
		config = self:getConfig(),
		tableid = self.tableid,
		seat_player = seat_players,
		state = 2,
	}	
	local data = {niuniu_status_res = status}
	self:sendToTable(data,'ntTableInfo')
	--self:sendMessage(0,data)
end

function Machine:ntStart(playerid,card)
	print("__________niuniu_start")
	local data = {niuniu_nt_start={
 		tableid = self.tableid,	
		card_data = card,
		paijuid = self.paijuid,
	}}
	self:sendMessage(playerid, data)
end

function Machine:ntBank()
	local data = {niuniu_nt_bank={
 		tableid = self.tableid,	
 		-- rates = {1},
	}}
	-- self:sendToTable(data)
	local tbRate = {}
	local chip = 0
	for playerid,player in pairs(self.player_list) do 
		if player   then 	
			tbRate = {}
			--防止坐庄不够赔 6牌型最大赔率
			chip = 0
			for k,v in pairs(self.tbBankRates) do 
				chip = self.bottomNum * v * (self.playerNum-1) * self.maxBetRate * 6
				if chip < player.chip then 
					table.insert(tbRate,v)
				end
			end
			if not next(tbRate) then 
				tbRate = {1}
			end
			data.niuniu_nt_bank.rates = tbRate
			player.tbBankRates = table.copy(tbRate)
			self:sendMessage(playerid,data)		
		end	
	end	
end

function Machine:ntBankok(playerid,rate,isbanker,tbSeat)
	print("__________niuniu_nt_bankok")
	if tbSeat and #tbSeat < 2 then 
		tbSeat = nil
	end
	local seatid = self:getPlayerSeatId(playerid)
	if isbanker and not tbSeat then 
		--tbSeat={seatid}
	end	
	local data = {niuniu_nt_bankok={
 		tableid = self.tableid,	
 		seatid = seatid,
 		rate = rate,
 		banker = isbanker,
 		rob_list = tbSeat,
	}}
	self:sendToTable(data)	
end

function Machine:ntBet()
	print("__________niuniu_nt_bet")
	local data = {niuniu_nt_bet={
 		tableid = self.tableid,	
 		-- rates = self.tbBetRates,
	}}
	-- self:sendToTable(data)
	local tbRate = {}
	local chip = 0
	for playerid,player in pairs(self.player_list) do 
		if player  then 	
			tbRate = {}
			--防止玩家下注不够赔
			for k,v in pairs(self.tbBetRates) do 
				chip = self.bottomNum * v * self.bankerRate * 6
				if chip  < player.chip and chip < self.banker.chip then 
					table.insert(tbRate,v)
				end
			end
			if not next(tbRate) then 								
				for k,v in pairs(self.tbBetRates2) do 
					chip = self.bottomNum * v * self.bankerRate * 6
					if chip  < player.chip and chip < self.banker.chip then 
						table.insert(tbRate,v)
					end
				end					
			end
			if not next(tbRate) then
				tbRate = {1}
			end
			data.niuniu_nt_bet.rates = tbRate
			player.tbBetRates = table.copy(tbRate)
			self:sendMessage(playerid,data)		
		end	
	end
end

function Machine:ntBetok(seatid,rate)
	print("__________niuniu_nt_betok",seatid,rate)
	local data = {niuniu_nt_betok={
 		tableid = self.tableid,	
 		seatid = seatid,
 		rate = rate,
	}}
	-- for k,v in pairs(self.tbPlayer) do 
	-- 	self:sendMessage(v, data)
	-- end	
	self:sendToTable(data)
	--self:sendMessage(0,data)
end

function Machine:ntComb(playerid,card)
	print("__________niuniu_nt_comb")
	local data = {niuniu_nt_comb={
 		tableid = self.tableid,	
 		card_data = card,
	}}
	self:sendMessage(playerid, data)
	
end

function Machine:ntCombok(playerid)
	local seatid = self:getPlayerSeatId(playerid)
	local data = {niuniu_nt_combok={
 		tableid = self.tableid,	
 		seatid = seatid,
	}}
	self:sendToTable(data)	
end

function Machine:ntEnd()
	print("__________nt_niuniu_end",self.tbNiuRes)
	local card = {}
	local seat_list = {}
	local win_score = {}
	local card_type = {}
	local seat_chip = {}
	local player
	local broadcast

	for k,v in pairs(self.tbNiuRes) do
		table.insert(seat_list,k)
		for _,c in pairs(v.card) do 
			table.insert(card,c)
		end
		table.insert(card_type,self.rule:getCardType(v.weight))
		if not self.tbWinScore[k] then 
			self.tbWinScore[k] = 0
		end
		table.insert(win_score,""..self.tbWinScore[k])
		table.insert(seat_chip,""..self.player_list[self.tbPlayer[k]].chip)
	end

	local data = {niuniu_nt_end={
 		tableid = self.tableid,	
		card_data = card,
		seat_list = seat_list,
		win_score = win_score,
		card_type = card_type,
		seat_chip = seat_chip,
	}}
	print("##########ntEnd########",data)
	self:sendToTable(data)	
	--赢得入场分*5 给跑马灯
	for k,v in pairs(self.tbWinScore) do 
		if v > self.minChip * 3 then 
			player = self:getPlayerBySeat(k)
		 	broadcast = {
				nt_broadcast = {
					id = 1,
				 	content = '恭喜['..player.nick..']在牛牛游戏中获得金币'..v,
				 }
			}			
			self.nodeMessage:broadcastAll(broadcast)
		end
	end
	
end

function Machine:ntRest()
	--print("__________nt_niuniu_rest")
	local data = {niuniu_nt_rest={
 		tableid = self.tableid,	
	}}
	self:sendToTable(data)	
end

-------------------------------------------------------------------------------
-- public
-------------------------------------------------------------------------------

--坐下
function Machine:sitDown( playerid )
	local tbSeat = {}
	for id=1,self.maxSeatNum do 
		local seat_userid = self.seat_list[id]
		if not seat_userid or seat_userid == 0 then 
			table.insert(tbSeat,id)
		end
	end
	mix_array(tbSeat) --随机位置
	local seatid
	if #tbSeat > 0 then 
		seatid = tbSeat[1]
	else
		self.player_list[playerid] = nil
		return false
	end
	local player = self.player_list[playerid]
	if player then
		self.seat_list[seatid] = playerid
		player.seatid = seatid
	end
	print(player)
	print("_______niuniu_nt_seat_change____")
	local seatPlayer = self:getSeatPlayer(player)

	local data = {niuniu_nt_seat_change = {
		tableid = self.tableid,
		seatid = seatid,
		seat_player = seatPlayer,
		leave = false,
	}}
	self:sendToOther(playerid,data)
	self:updatePlayerNum()
	return true
end

--离座
function Machine:sitUp(playerid)
	local seatid = 0
	if playerid>0 then
		local player = self.player_list[playerid]
		if player then
			seatid = player.seatid
			player.seatid = 0
		end
	end
	self.seat_list[seatid] = nil
	self.player_list[playerid] = nil

	local data = {niuniu_nt_seat_change = {
		tableid = self.tableid,
		seatid = seatid,
		leave = true,
	}}
	self:sendToAll(playerid,data)
	self:updatePlayerNum()
end

--离线清除
function Machine:removeDisconnect()
	for k,v in pairs(self.player_list) do 
		if v.disconnect then 	
			self:sendGate(v, 'update_tableid', 0)
			self:sitUp(k)
			self.player_list[k] = nil											
			print("踢走离线玩家#######",k)		
		end
	end
end

function Machine:removePlayer()
	--1筹码不够入场底线时踢出
	--2没准备好的玩家踢出
	--3离线的玩家踢出
	for k,v in pairs(self.player_list) do 
		if v.disconnect or not v.ready or  v.chip < self.minChip   then 			
			if  v.chip < self.minChip  then 
				local data = {nt_kick_table = {
					playerid = k,
					content = '金币不足请离场！',
				}}
				self:sendMessage(k,data)
			end				
			-- --3场无操作踢走
			-- if v.noOperNum > 3 then 
			-- 	local data = {nt_kick_table = {
			-- 		playerid = k,
			-- 		content = '您3局未操作，将自动退出游戏。',
			-- 	}}
			-- 	self:sendMessage(k,data)
			-- end

			--设置玩家所在桌子id为0	
			self:sendGate(v, 'update_tableid', 0)
			self:sitUp(k)
			self.player_list[k] = nil		
			print("牛牛踢走掉线 or 没准备好 or 筹码不够#######",k)
		end
	end
end

--取桌子id
function Machine:getTableId()
	return self.tableid
end

--取玩家
function Machine:getPlayer(playerid)
	--print("___111______self.player_list__",self.player_list,playerid)
	if not playerid then return nil end
	return self.player_list[playerid]
end

--通过座位取玩家
function Machine:getPlayerBySeat(seatid)
	local playerid = self.seat_list[seatid]
	if not playerid then return end
	return self.player_list[playerid]
end

--加入玩家
function Machine:addPlayer(info)
	local player = table.copy(info)
	player.noOperNum = 0 --未操作的局数
	player.opered = false --这局是否有操作
	self.player_list[player.playerid] = player

	-- local tb = {0x37,0x3a,0x08,0x38,0x1d}
	-- print("_____________1____",self.rule:getNiu(tb))
	-- local tb = {0x01,0x23,0x15,0x2c,0x3d}
	-- print("_____________2____",self.rule:getNiu(tb))	
	
	return player
end

--取库存表
function Machine:getStock()
	local stock = self:calldb('get_stock',self.gameid)
	if not next(stock) then 
		stock = {
			gameid=self.gameid,
			pool = 0,
			bottom = 1000,
			top = 100000,
			tip = 0,
		}
		self:calldb('add_stock',stock)		
		stock = self:calldb('get_stock',self.gameid)
	end
	self.stock = stock	
end

--计算机器人输赢
function Machine:robotSettlement()
	local system_earn = 0 --007赢的钱
	local tip = 0 --服务费
	local bankNiu = self.tbNiuRes[self.bankerSeatid]	
	local playerWeight
	local bottomNum = self.bankerRate*self.bottomNum
	local bankWin
	local banker = self:getPlayer(self.bankerid)	
	for k, v in pairs(self.tbPlayer) do 
		player = self.player_list[v]
		playerWeight = self.tbNiuRes[k].weight			
		-- print("__22222222______banker.robot__________",banker.robot,player.robot)
		if v == self.bankerid then 
		elseif banker.robot then 
		    --庄为机器人
		    if not player.robot  then 
				settleNum = bottomNum * self.tbPlayerBet[v] 			
				--庄赢
				if bankNiu.weight > playerWeight then 
					settleNum = settleNum * self.rule:getRate(bankNiu.weight)	
					--如果玩家身上钱不够
					if player.chip < settleNum then 
						settleNum = player.chip
					end
					system_earn = system_earn + settleNum				
				else
					settleNum = settleNum * self.rule:getRate(playerWeight)			
					system_earn = system_earn - settleNum				
				end		
			end
			-- print("___settleNum___",settleNum)
		elseif player.robot then 
			--庄为玩家
			settleNum = bottomNum * self.tbPlayerBet[v] 
			--庄赢
			if bankNiu.weight > playerWeight then 
				settleNum = settleNum * self.rule:getRate(bankNiu.weight)				
				system_earn = system_earn - settleNum						
			else
				settleNum = settleNum * self.rule:getRate(playerWeight)		
				if banker.chip < settleNum then 
					settleNum = banker.chip
				end					
				system_earn = system_earn + settleNum				
			end				
		end		
	end
	if system_earn > 0 then 
		system_earn = system_earn * (1-self.tipRate)
		tip = system_earn * self.tipRate
	end
	return system_earn, tip
end

--检查库存
function Machine:checkStock()
	--1.发牌后预先开牌,机器人和普通人间输赢计算 
	--2.如果库存够赔付正常开牌
	--3.如果库存不够换牌的位置再计算
	self:getStock()
	if not self.stock or not next(self.stock) then --无库存控制
		return false
	end 
	print("____2222222__库存______self.stock_______",self.stock)
	local stock = self.stock
	local banker = self:getPlayer(self.bankerid)
	local function get_earn()	
		local pool = stock.pool
		local bottom = stock.bottom
		local system_earn = self:robotSettlement()	
		if system_earn == 0 then --无人在打
			return true
		end		
		if pool <= bottom then --库存低于底线时一率杀
			if system_earn >= 0 then 
				return true
			end
			return false
		end
		--库存 + 007输赢  > 0 可开牌
		local earn = pool  + system_earn
		--print("_____________earn ___",earn,inventory,system_earn)
		if system_earn == 0 then --没有机器人
			return true
		elseif earn > 0 then
			--self.stock.pool = earn
			print("__2222222222222______pool___",pool,self.stock)
			return true
		end
		return false
	end

	print("_________________get_earn_____________")
	local res = get_earn()
	if res then
		return true
	end
	print("___________第一道防线____")
	--1.换牌位置 
	local tbLastCard = {}	
	for k,v in pairs(self.tbSeatCard) do 
		table.insert(tbLastCard,v[5])		
	end
	local tbPermute = getPermutation(tbLastCard)
	for _,tbLastCard in pairs(tbPermute) do 
		local i = 1
		for k,v in pairs(self.tbSeatCard) do 
			v[5] = tbLastCard[i]
			self.tbNiuRes[k] = self.rule:getNiu(v)
			if  get_earn() then
				return true
			end 			
			i = i + 1
		end
	end
	print("___________第二道防线____")	
	--2改变最后一张牌给出一个最大牌型
	local card = self.tbSeatCard[self.bankerSeatid]
	--2.
	if banker.robot then 
		--给到最大牌
		card = self.rule:getBestCard(card)
	else
		card = self.rule:getWorstCard(card)
	end
	self.rule:printCard(card)
	self.tbSeatCard[self.bankerSeatid] = card	
	self.tbNiuRes[self.bankerSeatid] = self.rule:getNiu(card)
	local res = get_earn()
	if res then
		return true
	end
	print("___________第三道防线____")	
	--3所有机器人通过改变最后一张牌取到最大牌型，玩家取到最小牌型
	local card
	local player
	local maxWeight = 0
	if banker.robot then 
		for k,v in pairs(self.tbPlayer) do 			
			player = self.player_list[v]
			if not player.robot then 
				card = self.rule:getWorstCard(self.tbSeatCard[k])
				self.tbSeatCard[k] = card
				self.tbNiuRes[k] = self.rule:getNiu(card)
				if self.tbNiuRes[k].weight > maxWeight then 
					maxWeight = self.tbNiuRes[k].weight 
				end
				print("____@@@@______111111___")
				self.rule:printCard(card)
			end
		end
	else
		for k,v in pairs(self.tbPlayer) do 			
			player = self.player_list[v]
			if player.robot then 
				card = self.rule:getBestCard(self.tbSeatCard[k])
				self.tbSeatCard[k] = card
				self.tbNiuRes[k] = self.rule:getNiu(card)
				print("_____@@@@_____222222___")
				self.rule:printCard(card)
			end
		end
	end
	local res = get_earn()
	if res then
		return true
	end
	print("___________第四道防线____")	
	--4玩家是炸弹的情况，给机器人一个5花牛
	local bankNiu = self.tbNiuRes[self.bankerSeatid]	
	if banker.robot then 
		print("__111_________")
		--从剩下的牌中选出一个5花牛
		local card = self.rule:getBigerWuhua(bankNiu.card)
		if card then 
			self.tbSeatCard[self.bankerSeatid] = card	
			self.tbNiuRes[self.bankerSeatid] = self.rule:getNiu(card)
			self.rule:printCard(card)
		end
	else
		print("__222_________")
		local playerNiu
		for k,v in pairs(self.tbPlayer) do 			
			player = self.player_list[v]
			if player.robot then 
				playerNiu = self.tbNiuRes[k] 
				local card = self.rule:getBigerWuhua(playerNiu.card)
				if card then 
					self.tbSeatCard[k] = card	
					self.tbNiuRes[k] = self.rule:getNiu(card)
					self.rule:printCard(card)
				end
			end
		end
	end
	local res = get_earn()
	if res then
		return true
	end	

	log.error('___error_________________库存控制失败了_______'.. json.encode(self.tbNiuRes))
	print("___error_________________库存控制失败了______________________")
	return false
end

----------------------------------
-- 流水记录
----------------------------------


----------------------------------
-- 牌局记录
----------------------------------
function Machine:paijuRecord()
	local playerid 
	local seatid 
	local win = 0
	local cards
	local cardType
	local player
	for k,v in pairs(self.tbPlayer) do 
		player = self.player_list[v]
		playerid = player.playerid		
		seatid = player.seatid
		win = 0
		if self.tbWinScore[seatid] > 0 then 
			win = 1
		end
		cards = self.tbNiuRes[seatid].card
		cardType = self.rule:getCardTypeText(self.tbNiuRes[seatid].weight)
	    --牌局记录写到redis 
		local record = {
			_type = "playercard" .. self.gameid,
			mid = playerid,
			appid = player.appid,
			channelid = player.channelid,			
			gameid = self.gameid,
			levelid = self.roomid,
			tableid = self.tableid,
			cardid = self.paijuid,
			before = self.tbBeforeStart[playerid],
			after = player.chip,
			iswin = win,
			optnum = self.tbWinScore[seatid],
			updatetime = os.time(),			
			cards = cards,			
			cardtype = cardType,
		}
		send_redis({ "rpush", "logs:queue_list", json.encode(record) }, 1)
	end

end

----------------------------------
-- 数据操作
----------------------------------
function Machine:calldb(cmd,...)
	return skynet.call('dbmgr_service','lua',cmd,...)	
end

function Machine:senddb(cmd,...)
	skynet.send('dbmgr_service','lua',cmd,...)	
end

-----------------------------------------------------------------------------------

--当前操作所剩余的时间
function Machine:getOperTime()
	local time = self.status_time[self.fsm:get()] - (os.time() - self.operStartTime)
	if time < 0 then 
		time = 0
	end
	return time
end

--当前状态
function Machine:getState()
	return self.fsm:get()
end

--状态对应的数字
function Machine:getStateNum()
	local state = self:getState()
	for k, v in pairs(self.gameStateTransitionTable) do 
		if state == v[1] then 
			return k
		end
	end
	return 
end

--桌子相关配置
function Machine:getConfig()


	return {
		star_time	= self.status_time.star,	-- 开始时间
		bank_time	= self.status_time.bank,	-- 抢庄时间
		bet_time	= self.status_time.bet,		-- 下注时间
		comb_time	= self.status_time.open,	-- 组牌时间
		end_time	= self.status_time.settlement,	-- 结算时间
		rest_time	= self.status_time.rest, 		-- 休息时间
		bottom_num	= ""..self.bottomNum,	-- 底分			
	}
end

--取桌子状态
function Machine:getTableStatus(playerid)

	local seatid = self:getPlayerSeatId(playerid)
	local tbCards = {}
	-- local tbBank = {}
	-- local tbBet = {}
	local seat_players = {}
	for seat_id,id in pairs(self.seat_list) do
		-- tbBank[seat_id] = -1
		-- tbBet[seat_id] = -1		
		if id>0 then
			local normalPlayer = self:getSeatPlayer(self.player_list[id])
			local seatPlayer = table_clone(normalPlayer)
			seatPlayer.isbanker = false
			seatPlayer.rate = self.tbPlayerBet[id] or 0
			if id == self.bankerid then 
				seatPlayer.isbanker = true
				seatPlayer.rate = self.bankerRate
			end
			seatPlayer.card_data = table_clone(self.tbSeatCard[k] or {})
			table.insert(seat_players,seatPlayer)
		end
	end	

	-- for k,v in pairs(self.tbBankerRate) do
	-- 	tbBank[self:getPlayerSeatId(v[2])] = v[1]
	-- end
	-- for k,v in pairs(self.tbPlayerBet) do 
	-- 	tbBet[self:getPlayerSeatId(k)] = v
	-- end
	local status = {
		state = 1, --self:getStateNum(),			
		config = self:getConfig(),
		tableid = self.tableid,
		time = self:getOperTime(),
	}	
	if self:getState() ~= "settlement" then 
		for k,v in pairs(tbCards) do 
			if seatid ~= k then 
				for i,j in pairs(v) do 
					j = -1 
				end
			end
		end
	end

	-- if self:getState() == "bank" then
	-- 	status.bank_state = {rates=self.tbBankRates,seat_rates=tbBank}
	-- end
	-- if self:getState() == "bet" then		
	-- 	status.bet_state = {rates=self.tbBetRates,seat_rates=tbBet}
	-- end
	local data = self:visitorMsg()
	if not data then
		data = {}
	end
	status.visitor_msg = data
	status.seat_player = seat_players
	--print("Table status################",status)	
	return status
end

--设置抢庄
function Machine:setBanker(playerid,rate)
	if self.fsm:get() ~= 'bank' then 
		return false
	end
	if not rate or rate < 0 then
		return false
	end

	local rateOk 
	local player = self.player_list[playerid]
	player.opered = true
	for k,v in pairs(player.tbBankRates) do 
		if rate == v then 
			rateOk = true
			break
		end
	end
	if not rateOk and rate ~= 0 then 
		return false
	end
	if rate > 0 then
		table.insert(self.tbBankerRate,{rate,playerid})
	else
		table.insert(self.tbNoBanker,playerid)
	end
	local len = #self.tbBankerRate + #self.tbNoBanker
	self:ntBankok(playerid,rate,false)
	if self.playerNum > len then		
		return true	
	end
	--所有人抢庄或不抢操作完

	--没人抢庄,随机一个玩家做庄，1倍
	if #self.tbBankerRate == 0 then 		
		local tb = {}
		for k,v in pairs(self.tbPlayer) do 
			table.insert(self.tbBankerRate,{1,v})
		end		
	end
	if #self.tbBankerRate > 1 then 
		local sortfun = function(a,b)
			return a[1] > b[1]
		end			
		--print(self.tbBankerRate)
		table.sort(self.tbBankerRate,sortfun)
	end
	local tbRater = self.tbBankerRate[1]
	local tbBankPlayer = {tbRater[2]} --抢庄倍数最大的玩家
	local tbSeat = {self:getPlayerSeatId(tbRater[2])}
	for k,v in pairs(self.tbBankerRate) do 	--是否有多个倍数一样的
		if v[1] == tbRater[1] and v[2] ~= tbRater[2]  then 
			table.insert(tbBankPlayer,v[2])
			table.insert(tbSeat,self:getPlayerSeatId(v[2]))
		end
	end
	if #tbBankPlayer > 1 then
		table.mix(tbBankPlayer)
	end
	self.bankerid = tbBankPlayer[1]
	self.bankerRate = tbRater[1]
	self.banker = self.player_list[self.bankerid]
	self.bankerSeatid = self:getPlayerSeatId(self.bankerid)
	self:ntBankok(self.bankerid,self.bankerRate,true,tbSeat)
	self.fsm:fire("to_bankok")
	
	return true
end

--设置下注
function Machine:setPlayerBet(playerid,rate)
	local rateOk 
	if self.fsm:get() ~= 'bet' then 
		return false
	end
	if playerid == self.bankerid then --庄不得下注
		return false 
	end
	local player = self.player_list[playerid]
	player.opered = true
	for k,v in pairs(player.tbBetRates) do 
		if rate == v then 
			rateOk = true
			break
		end
	end
	if not rateOk then 
		return false
	end

	self.tbPlayerBet[playerid] = rate
	local len = table.size(self.tbPlayerBet)  
	self:ntBetok(self:getPlayerSeatId(playerid),rate)
	if self.playerNum - 1 > len then
		return true	
	end
	--所有人下完注
	self.fsm:fire("to_open")
	return true
end

--组牌完成
function Machine:setPlayerComb(playerid)
	if self.fsm:get() ~= 'open' then 
		return false
	end
	local player = self.player_list[playerid]
	if not player then 
		return false
	end
	player.opered = true	
	self:ntCombok(playerid)
	table.insert(self.tbPlayerComb,playerid)
	if self.playerNum > #self.tbPlayerComb then 
		return true
	end
	--所有人组牌完成
	self.fsm:fire("to_settlement")
end

--换牌
function Machine:setPlayerCard(playerid)
	if self.fsm:get() ~= 'open' then 
		return false
	end
	--每个玩家一局只能换一次
	if self.tbChangeNum[playerid] then 
		return false
	end
	self.tbChangeNum[playerid] = true

	local player = self.player_list[playerid]
	player.opered = true
	if player.silver < 2 then
		return false
	end		
	player.silver = player.silver - 2
	-- local ret, money = proxy_helper.call_oper_to_gate(playerid, 'reduce_rmb', 2)
	local money = self:callGate(player,'reduce_rmb', 2)
	local seatPlayer = self:getSeatPlayer(player)

	local data = {niuniu_nt_seat_change = {
		tableid = self.tableid,
		seatid = player.seatid,
		seat_player = seatPlayer,
		leave = false,
	}}
	self:sendToAll(playerid,data)

	self.tbSeatCard[player.seatid] = self.rule:getCard(5)
	self.tbNiuRes[player.seatid] = self.rule:getNiu(self.tbSeatCard[player.seatid])

	return true,self.tbSeatCard[player.seatid]
end

--取玩家座位id
function Machine:getPlayerSeatId(playerid)
	for k, v in pairs(self.seat_list) do 
		if v == playerid then
			return k
		end
	end
	return nil
end

--取牌
function Machine:getCard(playerid,num)
	-- if playerid == 10000033 then 
	-- 	return {0x0b,0x1b,0x2b,0x3b,0x0a}
	-- end
	local tbCard = {}
	local playerCard = self.gmcards[playerid] 
	--print("_______playerCard______",playerCard,playerid,num)
	local delCard = {}
	if playerCard and #playerCard>0 and self.tbCheatNum[playerid] > 0 then --有配牌		
		self.tbCheatNum[playerid] = self.tbCheatNum[playerid] - 1
		if self.tbCheatNum[playerid] == 0 then
			self.gmcards[playerid] = {}
		end	
		if num == 1 then 
			table.insert(tbCard,playerCard[5])
		else
			for i=1,num do 
				table.insert(tbCard,playerCard[i])
			end
		end
		return tbCard
	end
	return self.rule:getCard(num)
end

function Machine:setGmCard(playerid,cards,repeatNum)
	self.tbCheatNum[playerid] = repeatNum or 0
	if repeatNum  == 0 then
		self.gmcards[playerid] = {}
	else
		self.gmcards[playerid] = cards
	end

	print("_______cards#################___________________",cards)
end

function Machine:enterTable(playerid)
	print('玩家进入牌桌>>>>>>>>>>>',player_id)
	
end

function Machine:leaveTable(playerid)
	print('玩家离开牌桌>>>>>>>>>>>',playerid,self.tableid)
	self:sitUp(playerid)

end

--掉线
function Machine:disconnect(playerid)
	print('玩家掉线>>>>>>>>>>>',playerid,self.tableid)
	local player = self.player_list[playerid]
	--旁观者掉线马上踢出大厅
	if not player.playing and player.disconnect then 
		print("########不在游戏中直接踢走")	
		--注意服务间不要相互调用call
		self:sendGate(player, 'update_tableid', 0)
		self:sitUp(playerid)
		return true
	end	
	return false
end

--结束服务
function Machine:exit()
	self.nodeMessage:sendService('.proxy','clear_table',self.tableid)
	skynet.fork(function()
		skynet.sleep(300)
		skynet.exit()
	end)
end

--关服
function Machine:setClose(close)
	self.close = close
	if not self.closeHandler then 
		self.timer:unregister(self.closeHandler)
		self.closeHandler = nil
	end
	if close then 
		--定时踢出所有玩家后，关服
		local maxDelay = 5*60 --最大的等待时间
		local delay = 0		
		local callback = function()
			delay = delay + 1
			if delay > maxDelay then
				self.fsm:fire('to_rest') 
				self.fsm:set('rest')
				self:onRest()
			end		
			if self:getState() ~= "rest" and self:getState() ~= "wait" then 
				return
			end		
			for k,v in pairs(self.player_list) do 			
				local data = {nt_kick_table = {
					playerid = k,
					content = '游戏正在维护！',
				}}
				self:sendMessage(k,data)	
				--设置玩家所在桌子id为0	
				self:sendGate(v, 'update_tableid', 0)
				self:sitUp(k)
			end		
			self.timer:unregister(self.closeHandler)
			self:exit()
		end
		--1局玩完后关游戏
		self.closeHandler = self.timer:register(1 , nil, callback,true)
	end
end

----------------------------------------------------------------------------------------------
---------开始游戏
---------------------------------------------------------------------------------------------- 
function Machine:start()

	-- print("_1111111111__stock___________",self.stock)
	self.fsm:set("rest")
	self.fsm:fire("to_wait")
end

return Machine